package com.wanggsx.library.base.views.pagerscrollerNew1;

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;

/**
 * Created by wanggsx on 15/12/9.
 */
public class HorizontalPagerScroller extends HorizontalScrollView {

    private Context mContext;
    public LinearLayout mContainer;
    private ScrollListener mListener;
    private int lastOldPosition = -1;

    private int MOVE_SMALL_DISTANCE = 40;

    public HorizontalPagerScroller(Context context) {
        super(context);
    }

    public HorizontalPagerScroller(Context context, AttributeSet attrs) {
        super(context, attrs);
        mContext = context;
        setHorizontalScrollBarEnabled(false);
    }

    /**
     * 初始化容器的尺寸及位置
     *
     * @param width        宽度
     * @param height       高度
     * @param marginLeft   左边距
     * @param marginTop    上边距
     * @param marginRight  右边距
     * @param marginBottom 底边距
     */
    public void initScrollerLocation(int width, int height, int marginLeft, int marginTop, int marginRight, int marginBottom, ScrollListener l) {
        if (width >= 10) {
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(width, height);
            params.setMargins(marginLeft, marginTop, marginRight, marginBottom);
            setLayoutParams(params);
        }
        mListener = l;
    }

    /**
     * 设置监听事件，用于绑定数据
     *
     * @param l
     */
    public void setListener(ScrollListener l) {
        mListener = l;
    }


    /**
     * 设置页数
     *
     * @param num         总页数
     * @param layoutId    布局文件id
     * @param width       页宽
     * @param height      页高
     * @param marginLeft  页的左外边距(最后一个页的右外边距同左，其余右边距为0)
     * @param paddingLeft 容器的左内边距(右内边距同左)
     */
    public void initPagerLocation(int num, int layoutId, int width, int height, int marginLeft, int paddingLeft) {
        Log.d("wan", "wanggsx 初始化pager");
        removeAllViews();
        totalPage = num;
        currentPageIndex = 0;
        originX = 0;
        scrollerPaddingLeftOrRight = paddingLeft;
        pagerLayoutId = layoutId;
        pagerWidth = width;
        pagerHeight = height;
        pagerMarginLeft = marginLeft;
        //从一个pager到另一个pager的实际距离
        pagerTotalWith = width + marginLeft;
        mContainer = new LinearLayout(mContext);
        addView(mContainer);
        resetContainerSize(totalPage);
        if (totalPage >= 3) {
            for (int i = 0; i <= 2; i++) {
                View child = getViewFromLayout(null, i);
                ((LinearLayout) mContainer.getChildAt(i)).addView(child);
            }
        } else if (totalPage == 2) {
            View child = getViewFromLayout(null, 0);
            ((LinearLayout) mContainer.getChildAt(0)).addView(child);
            View child1 = getViewFromLayout(null, 1);
            ((LinearLayout) mContainer.getChildAt(1)).addView(child1);
        } else if (totalPage == 1) {
            View child = getViewFromLayout(null, 0);
            ((LinearLayout) mContainer.getChildAt(0)).addView(child);
        }
    }

    private void resetContainerSize(int pageCount) {
        int width = 2 * scrollerPaddingLeftOrRight + pagerMarginLeft + pagerTotalWith * pageCount;
        ViewGroup.LayoutParams params = mContainer.getLayoutParams();
        if (params == null) {
            params = new LinearLayout.LayoutParams(width, ViewGroup.LayoutParams.MATCH_PARENT);
        } else {
            params.width = width;
        }
        int hasSize = mContainer.getChildCount();
        if (hasSize < pageCount) {
            int deltSize = pageCount - mContainer.getChildCount();
            for (int i = 0; i < deltSize; i++) {
                int thisIndex = hasSize + i;
                LinearLayout layout = new LinearLayout(mContext);
                LinearLayout.LayoutParams params1 = new LinearLayout.LayoutParams(pagerWidth, pagerHeight);
                params1.setMargins(pagerMarginLeft, 0, (totalPage == thisIndex + 1) ? pagerMarginLeft : 0, 0);
                layout.setLayoutParams(params1);
                layout.setTag(thisIndex);
                layout.setOrientation(LinearLayout.HORIZONTAL);
                mContainer.addView(layout);
            }
        } else if (hasSize > pageCount) {
            int deltSize = hasSize - pageCount;
            for (int i = 0; i < deltSize; i++) {
                mContainer.removeViewAt(mContainer.getChildCount() - 1);
            }
        }
        mContainer.setPadding(scrollerPaddingLeftOrRight, 0, scrollerPaddingLeftOrRight, 0);
        mContainer.setLayoutParams(params);
    }

    private int pagerLayoutId, pagerWidth, pagerHeight;

    private View getViewFromLayout(View view, int position) {
        View child = view;
        if (view == null) {
            child = LayoutInflater.from(mContext).inflate(pagerLayoutId, null);
            ViewGroup.LayoutParams params = child.getLayoutParams();
            if (params == null) {
                params = new ViewGroup.LayoutParams(pagerWidth, pagerHeight);
            } else {
                params.width = pagerWidth;
                params.height = pagerHeight;
            }
            child.setLayoutParams(params);
        }
        mListener.setViewData(position, child);
        return child;
    }

    public void setPageSize(int pageSize) {
        lastOldPosition = totalPage;
        totalPage = pageSize;
        resetContainerSize(totalPage);
    }

    public int getCurrentPageIndex() {
        return currentPageIndex;
    }

    private int totalPage, currentPageIndex, pagerTotalWith, scrollerPaddingLeftOrRight, pagerMarginLeft;
    private float startMoveX, scrollDistance, originX;
    private boolean tfIsFirstMove = true;

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        getParent().requestDisallowInterceptTouchEvent(true);
        return super.onInterceptTouchEvent(ev);
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        if (mContainer == null) return false;
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                startMoveX = ev.getX();
                tfIsFirstMove = false;
                break;
            case MotionEvent.ACTION_UP:
                scrollDistance = ev.getX() - startMoveX;
                if (scrollDistance > 0) {
                    //向右滑
                    if (scrollDistance > MOVE_SMALL_DISTANCE) {
                        if (currentPageIndex >= 1) {
                            mListener.onScrollToFront(--currentPageIndex);
                            if (currentPageIndex >= 1) {
                                ((LinearLayout) mContainer.getChildAt(currentPageIndex - 1)).removeAllViews();
                                ((LinearLayout) mContainer.getChildAt(currentPageIndex - 1)).addView(getViewFromLayout(null, currentPageIndex - 1));
                                if (currentPageIndex <= totalPage - 3) {
                                    ((LinearLayout) mContainer.getChildAt(currentPageIndex + 2)).removeAllViews();
                                }
                            }
                        }
                    }
                } else {
                    //向左滑
                    if (scrollDistance < -MOVE_SMALL_DISTANCE) {
                        if (currentPageIndex <= totalPage - 2) {
                            mListener.onScrollToNext(++currentPageIndex);
                            if (currentPageIndex <= totalPage - 2) {
                                //如果已经有新数据过来，应该更新最后一个pagerIndex
                                if (lastOldPosition >= 0) {
                                    //更新最后一个pager
                                    LinearLayout layout = (LinearLayout) mContainer.getChildAt(lastOldPosition - 1);
                                    LinearLayout.LayoutParams params1 = new LinearLayout.LayoutParams(pagerWidth, pagerHeight);
                                    params1.setMargins(pagerMarginLeft, 0, 0, 0);
                                    layout.setLayoutParams(params1);
                                    lastOldPosition = -1;
                                }
                                //添加下一个view
                                ((LinearLayout) mContainer.getChildAt(currentPageIndex + 1)).removeAllViews();
                                ((LinearLayout) mContainer.getChildAt(currentPageIndex + 1)).addView(getViewFromLayout(null, currentPageIndex + 1));
                                //移除最前面的一个view
                                if (currentPageIndex >= 2) {
                                    ((LinearLayout) mContainer.getChildAt(currentPageIndex - 2)).removeAllViews();
                                }
                            }
                        }
                    }
                }
                originX = pagerTotalWith * currentPageIndex;
                smoothScrollTo((int) (originX), 0);
                tfIsFirstMove = true;
                break;
            case MotionEvent.ACTION_MOVE:
                if (tfIsFirstMove) {
                    startMoveX = ev.getX();
                    tfIsFirstMove = false;
                }
                originX = pagerTotalWith * currentPageIndex;
                float scrollDistance = ev.getX() - startMoveX;
                scrollTo((int) (originX - scrollDistance), 0);
                break;
            case MotionEvent.ACTION_CANCEL:
                originX = pagerTotalWith * currentPageIndex;
                smoothScrollTo((int) originX, 0);
                tfIsFirstMove = true;
                break;
        }
        return true;
    }

    public int[] getPagerWithHeight() {
        int[] pageWH = new int[2];
        pageWH[0] = pagerWidth;
        pageWH[1] = pagerHeight;
        return pageWH;
    }

    public void refreshViewData(int position) {
        LinearLayout view = (LinearLayout) mContainer.getChildAt(position);
        view.removeAllViews();
        view.addView(getViewFromLayout(null, position));
    }

    public void scrollToPageIndex(int position) {
        if (totalPage == 0) {
            return;
        } else if (position == 0 && totalPage == 0 || currentPageIndex == position) {
            refreshViewData(position);
            return;
        }
        int oldPos = currentPageIndex;
        currentPageIndex = position;
        originX = pagerTotalWith * currentPageIndex;
        //创建
        ViewGroup view = null;
        if (position - 1 >= 0) {
            view = (ViewGroup) mContainer.getChildAt(position - 1);
            view.removeAllViews();
            view.addView(getViewFromLayout(null, position - 1));
        }
        view = (ViewGroup) mContainer.getChildAt(position);
        view.removeAllViews();
        view.addView(getViewFromLayout(null, position));
        if (position + 1 <= totalPage - 1) {
            view = (ViewGroup) mContainer.getChildAt(position + 1);
            view.removeAllViews();
            view.addView(getViewFromLayout(null, position + 1));
        }
        //删除
        if (oldPos - 1 >= 0 && isValidate(oldPos - 1)) {
            view = (ViewGroup) mContainer.getChildAt(oldPos - 1);
            view.removeAllViews();
        }
        if (isValidate(oldPos)) {
            view = (ViewGroup) mContainer.getChildAt(oldPos);
            view.removeAllViews();
        }
        if (oldPos + 1 <= totalPage - 1 && isValidate(oldPos + 1)) {
            view = (ViewGroup) mContainer.getChildAt(oldPos + 1);
            view.removeAllViews();
        }
        //滑动
        postDelayed(new Runnable() {
            @Override
            public void run() {
                smoothScrollTo((int) originX, 0);
            }
        }, 200);
    }

    private boolean isValidate(int tmpPos) {
        return tmpPos != currentPageIndex && tmpPos != currentPageIndex - 1 && tmpPos != currentPageIndex + 1;
    }

}
